package com.jdz.gxq.info.admin.logon.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import com.jdz.gxq.info.admin.logon.bo.MenuInfo;
import com.jdz.gxq.info.admin.logon.form.LogonForm;
import com.jdz.gxq.info.admin.logon.service.LogonService;
import com.jdz.gxq.info.admin.role.bo.User;
import com.jdz.gxq.info.common.action.CommonAction;
import com.jdz.gxq.info.common.bo.SessionUserInfo;
import com.jdz.gxq.info.common.constant.Constant;

public class LogonAction extends CommonAction {
	
	private LogonService logonService;

	public ActionForward doExecute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws java.lang.Exception {

		LogonForm logonForm = (LogonForm) form;
		
		String name = logonForm.getName();
		String password = logonForm.getPassword();
		
		name = "admin";
		password = "123456";
		
		if (StringUtils.isEmpty(name)) {
			ActionMessages messages = new ActionMessages();
			messages.add("name", new ActionMessage("errors.required", "用户名"));
			addErrors(request, messages);
			return mapping.getInputForward();
		}
		
		if (StringUtils.isEmpty(password)) {
			ActionMessages messages = new ActionMessages();
			messages.add("password", new ActionMessage("errors.required", "密码"));
			addErrors(request, messages);
			return mapping.getInputForward();
		}
		
		// 得到该用户信息
		User user = logonService.getUserByName(name);
		
		if (user == null) {
			ActionMessages messages = new ActionMessages();
			messages.add("name", new ActionMessage("error.userNotExisted"));
			addErrors(request, messages);
			return mapping.getInputForward();
		}
		
		// 验证密码
		if (!password.equals(user.getPassword())) {
			
			// 返回密码不正确
			ActionMessages messages = new ActionMessages();
			messages.add("password", new ActionMessage("error.passwordWrong"));
			addErrors(request, messages);
			return mapping.getInputForward();
		}
		
		// 得到用户权限
		List<MenuInfo> menuList = logonService.getMenusByRoleId(user.getRoleId());
		
		SessionUserInfo userInfo = new SessionUserInfo();
		userInfo.setUser(user);
		userInfo.setMenuList(menuList);
		
		HttpSession session = request.getSession();
		session.setAttribute(Constant.SEESION_USER_KEY, userInfo);
		
		return mapping.findForward("success");
	}

	public void setLogonService(LogonService logonService) {
		this.logonService = logonService;
	}
}
